package cn.fl.project.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IProprdLicenseService;
import cn.fl.preloan.condition.PrjPrdDtlQueryCondition;
import cn.fl.preloan.condition.PrjPrdLicInfoQueryCondition;
import cn.fl.preloan.condition.PrjPreAudInfoQueryCondition;
import cn.fl.preloan.dto.GetPrjPrdLicInfoListRequest;
import cn.fl.preloan.dto.GetPrjPrdLicInfoListResponseDTO;
import cn.fl.preloan.dto.PrjPrdDtlDTO;
import cn.fl.preloan.dto.PrjPrdLicInfoDTO;
import cn.fl.preloan.dto.prjpreaudinfo.PrjPreAudInfoDTO;
import cn.fl.preloan.dto.prjpreaudinfo.PrjPreAudInfoPageResponseDTO;
import cn.fl.preloan.prjpreaudinfo.IPrjPreAudInfoApiService;
import cn.fl.preloan.project.IPrjPrdDtlApiService;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjLnkCompService;
import cn.fl.project.utils.ValisityUtils;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjLnkCompVO;
import cn.fl.project.vo.PrjPreAudInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import flow.business.facade.flow.api.IFlowBusinessQueryApiService;
import flow.business.facade.flow.condition.SysFlowSHQueryCondition;
import flow.business.facade.flow.dto.SysFlowSHDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 预审
 * @Author: liumengmeng
 * @Date: 2020/9/3 9:34
 * @Version V1.0
 **/
@Controller
@RequestMapping("/project/prjPreAudInfo")
public class PrjPreAudInfoController {

    @Autowired
    private IPrjPreAudInfoApiService prjPreAudInfoService;

    @Autowired
    private IPrjBscInfoService prjBscInfoService;

    @Autowired
    private IPrjLnkCompService prjLnkCompService;

    @Autowired
    private ISysDictionaryService sysDictionaryService ;

    @Autowired
    private IPrjPrdDtlApiService prjPrdDtlApiService;

    @Autowired
    private IFlowBusinessQueryApiService flowBusinessQueryApiService;

    @Autowired
    private IProprdLicenseService proprdLicenseService;


    /**
     * 到预审新增tab页
     */
    @RequestMapping(value = "/toAddPreAudTabPage.do", method = { RequestMethod.GET})
    public ModelAndView toAddPreAudTabPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("toAddPreAudTabPage.跳转到预审tab页.request：{}" + JSONObject.toJSONString(request.getParameterMap())).info();
        ModelAndView view = new ModelAndView("project/prjpreaudinfo/addPreAudPage");
        String prjId = request.getParameter("prjId");
        String detailFlag = request.getParameter("detailFlag");
        //客户姓名自动带出
        PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(Long.valueOf(prjId));
        view.addObject("cstNm",prjBscInfoVO.getCstNm());
        view.addObject("cstId",prjBscInfoVO.getCstId());
        view.addObject("cstTypCd",prjBscInfoVO.getCstTypCd());
        view.addObject("prjTypCd",prjBscInfoVO.getPrjTypCd());
        view.addObject("prjId",prjId);
        view.addObject("detailFlag",detailFlag);
        BaseLogUtils.newLogger("toAddPreAudTabPage.跳转到预审tab页.view：{}" + JSONObject.toJSONString(view)).info();
        return view;
    }

    /**
     * 初始化列表
     */
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("initList.初始化预审信息页面request" + JSONObject.toJSONString(request.getParameterMap())).info();
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");
            String prjId = request.getParameter("prjId");
            String cstId = request.getParameter("cstId");
            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            PrjPreAudInfoQueryCondition condition = new PrjPreAudInfoQueryCondition();
            condition.setPrjId(Long.valueOf(prjId));
            if (StringUtils.isNotEmpty(cstId)){
                condition.setCstId(Long.valueOf(cstId));
            }
            condition.setIsDel(0);
            BaseLogUtils.newLogger("toAddPreAudTabPage.查询已保存的预审信息.condition：{}" + JSONObject.toJSONString(condition)).info();
            ResponseData<PrjPreAudInfoPageResponseDTO> responseData = prjPreAudInfoService.selectListPage(page.getEveryPage(), page.getCurrentPage(), condition);
            BaseLogUtils.newLogger("toAddPreAudTabPage.查询已保存的预审信息.list：{}" + JSONObject.toJSONString(responseData)).info();
            ListPageVO listPageVO = new ListPageVO();
            if (ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && responseData.getData() != null){
                PrjPreAudInfoPageResponseDTO data = responseData.getData();
                listPageVO.setRows(data.getList());
                listPageVO.setTotal(data.getTotalCount());
            }
            return listPageVO;
        } catch(Exception e){
            BaseLogUtils.newLogger("初始化项目列表数据异常,e:{}",e).error(LogExceptionEnum.API_CODE_0102,e);
        }
        return null;
    }

    /**
     * 到关联供应商页面
     */
    @RequestMapping(value = "/toAddSplPage.do", method = { RequestMethod.GET})
    public ModelAndView toAddSplPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("toAddSplPage.到关联供应商页面.request：{}" + JSONObject.toJSONString(request.getParameterMap())).info();
        ModelAndView view = new ModelAndView("project/prjpreaudinfo/addSplPage");
        String prjId = request.getParameter("prjId");
        view.addObject("prjId",prjId);
        BaseLogUtils.newLogger("toAddSplPage.跳转到供应商页面.prjId：{}" + prjId).info();
        return view;
    }

    /**
     * 到挂靠公司页面
     */
    @RequestMapping(value = "/toAddLnkCompPage.do", method = { RequestMethod.GET})
    public ModelAndView toAddLnkCompPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newLogger("toAddLnkCompPage.到挂靠公司页面.request：{}" + JSONObject.toJSONString(request.getParameterMap())).info();
        ModelAndView view = new ModelAndView("project/prjpreaudinfo/addLnkCompPage");
        String prjId = request.getParameter("prjId");
        String prjTypCd = request.getParameter("prjTypCd");
        String vehNo = request.getParameter("vehNo");
        String splId = request.getParameter("splId");
        view.addObject("prjId",prjId);
        view.addObject("prjTypCd",prjTypCd);
        view.addObject("vehNo",vehNo);
        view.addObject("splId",splId);
        BaseLogUtils.newLogger("toAddLnkCompPage.跳转到挂靠公司页面.prjId：{}" + prjId).info();
        return view;
    }

    /**
     * 保存预审信息
     *
     *   预审信息保存逻辑：均有：vin、若征信选择了挂靠，则挂靠公司必填
     *              1.二手车交易贷：车牌号非必填，供应商必填
     *              2.车抵贷线下：车牌号必填，供应商非必填
     *              3.内转交易贷：车牌号必填，供应商必填
     *              4.页面上车牌号不能重复
     *              5.页面上供应商和挂靠公司必须一致
     *
     */
    @RequestMapping(value = "/savePreAudInfo.do", method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public Object savePreAudInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String prjPreAudInfoList = request.getParameter("prjPreAudInfoList");
        String prjId = request.getParameter("prjId");
        String rcCstBscInfoId = request.getParameter("rcCstBscInfoId");
        BaseLogUtils.newLogger("保存预审信息.prjId:{},request：{}", prjId, JSONObject.toJSONString(request.getParameterMap())).info();
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);

        try {
            PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(Long.valueOf(prjId));
            BaseLogUtils.newLogger("查询项目信息.prjId:{},prjBscInfoVO：{}", prjId, JSONObject.toJSONString(prjBscInfoVO)).info();
            String prjTypCd = prjBscInfoVO.getPrjTypCd();

            //id-预审 关系map
            Map<Long,PrjPreAudInfoDTO> idAndPreMap = new HashMap<>();

            PrjPreAudInfoQueryCondition condition = new PrjPreAudInfoQueryCondition();
            condition.setPrjId(Long.valueOf(prjId));
            ResponseData<List<PrjPreAudInfoDTO>> responseData = prjPreAudInfoService.selectList(condition);
            BaseLogUtils.newLogger("查询当前项目已存的预审信息.prjId:{},responseData：{}", prjId, JSONObject.toJSONString(responseData)).info();
            if (ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && CollectionUtils.isNotEmpty(responseData.getData())){
                responseData.getData().forEach(dto -> {
                    idAndPreMap.put(dto.getId(),dto);
                });
            }

            List<PrjPreAudInfoVO> list = new ArrayList<>();
            if (StringUtils.isNotBlank(prjPreAudInfoList)) {
                list = JSON.parseArray(prjPreAudInfoList, PrjPreAudInfoVO.class);
                BaseLogUtils.newLogger("查询保存参数，prjId:{},list:{}",prjId, JSONObject.toJSONString(list)).info();
            }

            if (CollectionUtils.isNotEmpty(list)){
                if (list.size() > 10){
                    throw new BaseException("本业务最多允许新增10台车辆！");
                }
                PrjPreAudInfoVO prjPreAudInfoVO = list.get(0);
                Long lnkCompInfoId = prjPreAudInfoVO.getLnkCompId();
                Long splInfoId = prjPreAudInfoVO.getSplId();

                //1.校验vin不为空且不重复
                List<String> vinStr = list.stream().map(PrjPreAudInfoVO::getVin).collect(Collectors.toList());
                if (vinStr.contains(null) || vinStr.contains("")){
                    throw new BaseException("vin不能为空！");
                }
                if (vinStr.stream().distinct().count() < vinStr.size()){
                    throw new BaseException("vin重复，请核实！");
                }
                for (PrjPreAudInfoVO vo : list) {
                    List<String> vehNoStr = new ArrayList<>();
                    if ((prjTypCd.equals(PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL) || prjTypCd.equals(PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD)) && StringUtils.isEmpty(vo.getVehNo())) {
                        throw new BaseException("车牌号不能为空！");
                    }
                    if ((prjTypCd.equals(PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD) || prjTypCd.equals(PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD)) && null == vo.getSplId()) {
                        throw new BaseException("请选择供应商！");
                    }
                    if (StringUtils.isNotEmpty(vo.getVehNo())){
                        if (!vehNoStr.contains(vo.getVehNo())) {
                            vehNoStr.add(vo.getVehNo());
                        } else {
                            throw new BaseException("车牌号重复，请核实！");
                        }
                    }
                    if (!Objects.equals(splInfoId,vo.getSplId())){
                        throw new BaseException("供应商不一致，请核实！");
                    }
                    if (!Objects.equals(lnkCompInfoId,vo.getLnkCompId())){
                        throw new BaseException("挂靠公司不一致，请核实！");
                    }

                    //若页面上有新内容，需校验征信是否选择了挂靠
                    boolean flag = true;
                    if (null != vo.getId() && idAndPreMap.containsKey(vo.getId())){
                        PrjPreAudInfoDTO dto = idAndPreMap.get(vo.getId());
                        if (Objects.equals(vo.getVehNo(),dto.getVehNo()) && Objects.equals(vo.getVin(),dto.getVin())
                                && Objects.equals(vo.getSplId(),dto.getSplId()) && Objects.equals(vo.getLnkCompId(),dto.getLnkCompId())){
                            flag = false;
                        }
                    }
                    if (flag){
                        String vehNo = StringUtils.isEmpty(vo.getVehNo()) ? null : vo.getVehNo();
                        Long splId = StringUtils.isEmpty(vo.getSplId()) ? null : vo.getSplId();
                        BaseLogUtils.newLogger("校验征信是否已选挂靠prjId：{},vehNo:{},splId:{}", prjId, vehNo, splId).info();
                        DataResultDTO resultDTO = this.prjLnkCompService.selectRiskLnkList(Long.valueOf(prjId), vehNo, splId);
                        BaseLogUtils.newLogger("校验征信是否已选挂靠prjId：{}，resultDTO:{}", prjId, JSON.toJSONString(resultDTO)).info();
                        if(resultDTO != null){
                            String code = resultDTO.getCode();
                            if(BaseConstant.IS_YESNO_NO_STR.equals(code) && StringUtils.isEmpty(vo.getLnkCompId())){
                                throw new BaseException("保存失败，请逐一排查以下信息：</br>" +
                                        "1.请核实预审信息车牌号是否正确</br>" +
                                        "2.请核实预审信息是否维护挂靠公司</br>" +
                                        "3.请核实预审信息是否关联供应商");
                            }
                        }
                    }

                    //校验挂靠公司是否支持二手车项目
                    if (null != vo.getLnkCompId()){
                        String roleisEncrypt = this.sysDictionaryService.getRoleisEncrypt();
                        BaseLogUtils.newLogger("查询是否需要掩码prjId：{}，result:{}", prjId, roleisEncrypt).info();
                        int isMask = 0;
                        if(BaseConstant.IS_YESNO_YES_STR.equals(roleisEncrypt)){
                            isMask = 1 ;
                        }
                        BaseLogUtils.newLogger("查询挂靠公司详情，lnkCompId:{},isMask:{}", vo.getLnkCompId(), isMask).info();
                        PrjLnkCompVO prjLnkCompVO = this.prjLnkCompService.selectPrjLnkCompByIdAndIsMask(vo.getLnkCompId(), isMask);
                        BaseLogUtils.newLogger("查询挂靠公司详情，lnkCompId:{},lnkCompVo:{}", vo.getLnkCompId(), JSON.toJSONString(prjLnkCompVO)).info();
                        if (null != prjLnkCompVO) {
                            List<String> suppPrjTypCdList = prjLnkCompVO.getSuppPrjTypCdList();
                            if (CollectionUtils.isEmpty(suppPrjTypCdList) || !suppPrjTypCdList.contains("002")){
                                throw new BaseException("可支持项目挂靠类型不包含二手车，请核实！");
                            }
                        }
                    }
                    //校验vin，车牌号是否已被占用
                    if (StringUtils.isNotEmpty(vo.getVin())){
                        checkVinIsOccupy(vo.getVin(),vo.getPrjId());
                    }
                    if (StringUtils.isNotEmpty(vo.getVehNo())){
                        checkVehNoIsOccupy(vo.getVehNo(),vo.getPrjId());
                    }
                }

                PrjPreAudInfoDTO dto = null;
                for (PrjPreAudInfoVO vo : list) {
                    if (StringUtils.isNotEmpty(rcCstBscInfoId)){
                        vo.setRcCstBscInfoId(Long.valueOf(rcCstBscInfoId));
                    }
                    String vin = vo.getVin();
                    BaseLogUtils.newLogger("vin去空格，原:{}", vin).info();
                    vin = vin.replace(" ","");
                    BaseLogUtils.newLogger("vin去空格，后:{}", vin).info();
                    vo.setVin(vin.toUpperCase());
                    BaseLogUtils.newLogger("vin大小写转换，新:{}", vo.getVin()).info();
                    dto = new PrjPreAudInfoDTO();
                    BeanUtils.copyProperties(vo,dto);
                    if (null == vo.getId()){
                        dto.setCrtTm(new Date());
                        dto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                        dto.setCrtUsrName(CurrentThreadContext.getCurrentUserName());
                        BaseLogUtils.newLogger("新增预审信息.dto：{}" + JSONObject.toJSONString(dto)).info();
                        ResponseData<Integer> add = prjPreAudInfoService.add(dto);
                        BaseLogUtils.newLogger("新增预审信息.add：{}" + JSONObject.toJSONString(add)).info();
                        if (!add.getCode().equals(ResponseData.SUCCESS_CODE)){
                            throw new BaseException("保存失败！");
                        }
                    } else if (null != vo.getId()){
                        dto.setMdfTm(new Date());
                        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                        dto.setMdfUsrName(CurrentThreadContext.getCurrentUserName());
                        BaseLogUtils.newLogger("修改预审信息.dto：{}" + JSONObject.toJSONString(dto)).info();
                        ResponseData<Integer> modifyById = prjPreAudInfoService.modifyById(dto);
                        BaseLogUtils.newLogger("修改预审信息.add：{}" + JSONObject.toJSONString(modifyById)).info();
                        if (!modifyById.getCode().equals(ResponseData.SUCCESS_CODE)){
                            throw new BaseException("保存失败！");
                        }
                    }
                }
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("保存失败.DATA:" + ex.getMessage()).info();
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("savePreAudInfo.保存失败DATA:" + ex.getMessage()).info();
        }
        return result;
    }

    /**
     * 删除预审信息
     */
    @RequestMapping(value = "/removePreAudInfo.do", method = { RequestMethod.GET })
    @ResponseBody
    public Object removePreAudInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("删除预审信息.request：{}" + JSONObject.toJSONString(request.getParameterMap())).info();
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)){
            return new DataResultVO(BaseConstant.IS_YESNO_YES, "主键为空！");
        }
        try {
            BaseLogUtils.newLogger("删除预审信息.dto：{}" + id).info();
            ResponseData<Boolean> deleteById = prjPreAudInfoService.deleteById(Long.valueOf(id));
            BaseLogUtils.newLogger("删除预审信息.add：{}" + JSONObject.toJSONString(deleteById)).info();
            if (!deleteById.getCode().equals(ResponseData.SUCCESS_CODE)){
                throw new BaseException("删除失败！");
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("保存失败.DATA:" + ex.getMessage()).info();
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("savePreAudInfo.保存失败DATA:" + ex.getMessage()).info();
        }
        return result;
    }


    /**
     * 验证车牌号是否正确
     */
    @RequestMapping("/validVehNo.do")
    @ResponseBody
    public DataResultVO validVehNo(String vehNo){
        DataResultVO res = new DataResultVO();
        res.setSuccess(2);
        res.setInfo("车牌号有误，请重新输入！");
        if(StringUtils.isNotBlank(vehNo)){
            boolean checkRes = ValisityUtils.validityVehNo(vehNo);
            BaseLogUtils.newLogger("validVehNo校验车牌号:{" + vehNo + "} ,校验结果为:{" +checkRes+ "}");
            if(checkRes){
                res.setSuccess(1);
                res.setInfo("车牌号校验成功！");
            }
        }
        return res;
    }


    private void checkVinIsOccupy(String vin,Long prjId){
        if (StringUtils.isEmpty(vin) || null == prjId){
            throw new BaseException("项目id，vin不能为空！");
        }
        BaseLogUtils.newLogger("校验vin是否被占用.vin:{}",vin).info();
        PrjPreAudInfoQueryCondition condition = new PrjPreAudInfoQueryCondition();
        condition.setVin(vin);
        condition.setIsDel(0);
        ResponseData<List<PrjPreAudInfoDTO>> listResponseData = prjPreAudInfoService.selectList(condition);
        BaseLogUtils.newLogger("查询预审信息中vin是否被占用.vin:{},responseData:{}",vin,JSON.toJSONString(listResponseData)).info();
        List<PrjPreAudInfoDTO> prjPreAudInfoDTOS = null;
        if (null != listResponseData && ResponseData.SUCCESS_CODE.equals(listResponseData.getCode()) && CollectionUtils.isNotEmpty(listResponseData.getData())){
            prjPreAudInfoDTOS = listResponseData.getData().stream().filter(dto -> !prjId.equals(dto.getPrjId())).collect(Collectors.toList());
        }

        PrjPrdDtlQueryCondition queryCondition = new PrjPrdDtlQueryCondition();
        queryCondition.setVin(vin);
        //S010301、S010401、S010501、S0106020101、S01060203010101、S0106020201、S02
        //已正常结清、已提前结清、已强制结清、拖车已处置、优车已处置、已赎回结清、作废
        queryCondition.setPrdStsCds(Stream.of("S010301", "S010401", "S010501", "S0106020101", "S01060203010101", "S0106020201", "S02").collect(Collectors.toList()));
        BaseLogUtils.newLogger("查询dtl表中vin是否被占用.vin:{},condition:{}",vin,JSON.toJSONString(queryCondition)).info();
        ResponseData<List<PrjPrdDtlDTO>> responseData = prjPrdDtlApiService.searchList(queryCondition);
        BaseLogUtils.newLogger("查询dtl表中vin是否被占用.vin:{},responseData:{}",vin,JSON.toJSONString(responseData)).info();
        List<PrjPrdDtlDTO> prjPrdDtlDTOS = null;
        if (null != responseData && ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && CollectionUtils.isNotEmpty(responseData.getData())){
            prjPrdDtlDTOS = responseData.getData().stream().filter(dto -> !prjId.equals(dto.getPrjId())).collect(Collectors.toList());
        }
        if (CollectionUtils.isNotEmpty(prjPrdDtlDTOS)){
            prjPrdDtlDTOS.forEach( prjPrdDtlDTO -> {
                PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(prjPrdDtlDTO.getPrjId());
                throw new BaseException("当前vin已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
            });
        } else if (CollectionUtils.isNotEmpty(prjPreAudInfoDTOS) && CollectionUtils.isEmpty(prjPrdDtlDTOS)) {
            //若预审有，但dtl无，则进一步判断vin所在的项目状态
            for (PrjPreAudInfoDTO prjPreAudInfoDTO : prjPreAudInfoDTOS) {
                PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(prjPreAudInfoDTO.getPrjId());
                SysFlowSHQueryCondition flowSHQueryCondition = new SysFlowSHQueryCondition();
                flowSHQueryCondition.setDataId(prjPreAudInfoDTO.getPrjId());
                flowSHQueryCondition.setWordsInTheTable("PRJ");
                flowSHQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                flowSHQueryCondition.setStatus(BaseConstant.IS_YESNO_YES);
                BaseLogUtils.newLogger("查询流程记录表.vin:{},flowSHQueryCondition:{}",vin,JSON.toJSONString(flowSHQueryCondition)).info();
                List<SysFlowSHDTO> sysFlowSHDTOS = this.flowBusinessQueryApiService.searchFlowSHDTOList(flowSHQueryCondition);
                BaseLogUtils.newLogger("查询流程记录表.vin:{},sysFlowSHDTOS:{}",vin,JSON.toJSONString(sysFlowSHDTOS)).info();
                if (CollectionUtils.isEmpty(sysFlowSHDTOS)) {
                    throw new BaseException("当前vin已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
                } else {
                    SysFlowSHDTO sysFlowSHDTO = sysFlowSHDTOS.get(0);
                    if ("7".equals(sysFlowSHDTO.getAudStsCd()) || "8".equals(sysFlowSHDTO.getAudStsCd())
                            || "9".equals(sysFlowSHDTO.getAudStsCd()) || "10".equals(sysFlowSHDTO.getAudStsCd())) {
                        throw new BaseException("当前vin已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
                    }
                }
            }
        }
    }


    private void checkVehNoIsOccupy(String vehNo,Long prjId){
        if (StringUtils.isEmpty(vehNo) || null == prjId){
            throw new BaseException("项目id，车牌号不能为空！");
        }
        BaseLogUtils.newLogger("校验车牌号是否被占用.vehNo:{}",vehNo).info();
        PrjPreAudInfoQueryCondition condition = new PrjPreAudInfoQueryCondition();
        condition.setVehNo(vehNo);
        condition.setIsDel(0);
        ResponseData<List<PrjPreAudInfoDTO>> listResponseData = prjPreAudInfoService.selectList(condition);
        BaseLogUtils.newLogger("查询预审信息中车牌号是否被占用.vehNo:{},responseData:{}",vehNo,JSON.toJSONString(listResponseData)).info();
        List<PrjPreAudInfoDTO> prjPreAudInfoDTOS = null;
        if (null != listResponseData && ResponseData.SUCCESS_CODE.equals(listResponseData.getCode()) && CollectionUtils.isNotEmpty(listResponseData.getData())){
            prjPreAudInfoDTOS = listResponseData.getData().stream().filter(dto -> !prjId.equals(dto.getPrjId())).collect(Collectors.toList());
        }

        GetPrjPrdLicInfoListRequest listRequest = new GetPrjPrdLicInfoListRequest();
        listRequest.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        listRequest.setSysCd(CurrentThreadContext.getCurrentSysCd());
        PrjPrdLicInfoQueryCondition queryCondition = new PrjPrdLicInfoQueryCondition();
        queryCondition.setVehNo(vehNo);
        listRequest.setCondition(queryCondition);
        BaseLogUtils.newLogger("查询上牌中车牌号是否被占用.vehNo:{},listRequest:{}",vehNo,JSON.toJSONString(listRequest)).info();
        ResponseData<GetPrjPrdLicInfoListResponseDTO> responseData = proprdLicenseService.searchList(listRequest);
        BaseLogUtils.newLogger("查询上牌中车牌号是否被占用.vehNo:{},responseData:{}",vehNo,JSON.toJSONString(responseData)).info();
        List<PrjPrdLicInfoDTO> prjPrdLicInfoDTOS = null;
        if (null != responseData && ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && null != responseData.getData()){
            prjPrdLicInfoDTOS = responseData.getData().getPrjPrdLicInfoDTOS().stream().filter(dto -> !prjId.equals(dto.getPrjId())).collect(Collectors.toList());
        }
        List<String> collect = Stream.of("S010301", "S010401", "S010501", "S0106020101", "S01060203010101", "S0106020201", "S02").collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(prjPrdLicInfoDTOS)){
            prjPrdLicInfoDTOS.forEach( prjPrdLicInfoDTO -> {
                ResponseData<PrjPrdDtlDTO> dtoResponseData = prjPrdDtlApiService.selectById(prjPrdLicInfoDTO.getId());
                if (null != dtoResponseData && ResponseData.SUCCESS_CODE.equals(dtoResponseData.getCode()) && null != dtoResponseData.getData()){
                    if (null != dtoResponseData.getData().getPrjId()){
                        PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(dtoResponseData.getData().getPrjId());
                        if (!collect.contains(dtoResponseData.getData().getPrdStsCd())){
                            throw new BaseException("当前车牌号已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
                        }
                    }
                }
            });
        } else if (CollectionUtils.isNotEmpty(prjPreAudInfoDTOS) && CollectionUtils.isEmpty(prjPrdLicInfoDTOS)) {
            //若预审有，但dtl无，则进一步判断vin所在的项目状态
            for (PrjPreAudInfoDTO prjPreAudInfoDTO : prjPreAudInfoDTOS) {
                PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(prjPreAudInfoDTO.getPrjId());
                SysFlowSHQueryCondition flowSHQueryCondition = new SysFlowSHQueryCondition();
                flowSHQueryCondition.setDataId(prjPreAudInfoDTO.getPrjId());
                flowSHQueryCondition.setWordsInTheTable("PRJ");
                flowSHQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                flowSHQueryCondition.setStatus(BaseConstant.IS_YESNO_YES);
                BaseLogUtils.newLogger("查询流程记录表.vehNo:{},flowSHQueryCondition:{}",vehNo,JSON.toJSONString(flowSHQueryCondition)).info();
                List<SysFlowSHDTO> sysFlowSHDTOS = this.flowBusinessQueryApiService.searchFlowSHDTOList(flowSHQueryCondition);
                BaseLogUtils.newLogger("查询流程记录表.vehNo:{},sysFlowSHDTOS:{}",vehNo,JSON.toJSONString(sysFlowSHDTOS)).info();
                if (CollectionUtils.isEmpty(sysFlowSHDTOS)) {
                    throw new BaseException("当前车牌号已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
                } else {
                    SysFlowSHDTO sysFlowSHDTO = sysFlowSHDTOS.get(0);
                    if ("7".equals(sysFlowSHDTO.getAudStsCd()) || "8".equals(sysFlowSHDTO.getAudStsCd())
                            || "9".equals(sysFlowSHDTO.getAudStsCd()) || "10".equals(sysFlowSHDTO.getAudStsCd())) {
                        throw new BaseException("当前车牌号已被项目占用，占用项目名称为:" + prjBscInfoVO.getPrjNm());
                    }
                }
            }
        }
    }


}
